package cc.eddic.practice.concurrency;

import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Optional;
import java.util.regex.Pattern;

@Slf4j
public class LogItemParseTyq0811Impl implements LogItemParser {

    @Override
    public Optional<LogItem> parse(String line) {
        val m = PATTERN_LOG_LINE.matcher(line);
        if (!m.matches()) {
            log.error("Error parsing line: {}", line);
            return Optional.empty();
        }
        if (log.isDebugEnabled()) log.debug("正在解析 {}", line);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);
        LocalDateTime localDateTime = LocalDateTime.parse(m.group("timeZone"), formatter);

        return Optional.of(new LogItem(m.group("clientIP"), localDateTime, " ", m.group("method"), m.group("url"), new HashMap<>(), m.group("protocol"), Integer.parseInt(m.group("statusCode")), Long.parseLong(m.group("trafficSize")), m.group("referer"), m.group("userAgent")));
    }

    private static final Pattern PATTERN_LOG_LINE = Pattern.compile("(?<clientIP>.+) (?<hitMiss>.+) (?<responseTime>\\d+) \\[(?<timeZone>.+)] \"(?<method>\\w+) (?<url>.+) (?<protocol>\\S+?)\" (?<statusCode>\\d+) (?<trafficSize>\\d+) \"(?<referer>.*?)\" \"(?<userAgent>.*)\"", Pattern.UNICODE_CHARACTER_CLASS | Pattern.DOTALL);
}
